<?php

// 发送优惠码
// POST org.sendCode

namespace app\api\resource\org;
use think\Db;
use think\Session;
use app\common\lib\Sms;

class SendCode
{
    // 方法
    public $_method = ['POST'];
    // 前置
    public $_pre    = ['orgLogin'];
    // 描述
    public $_description = '发送优惠码';
    // 参数
    public $_param  = [
        'mobile' => '手机号',
    ];
    // 返回
    public $_return = [
        201 => '发送成功',
        400 => '该手机号尚有未使用的优惠码,不能重复发送',
        422 => '手机号必须|手机号格式不正确',
        500 => '服务器异常',
    ];

    public function run(&$request)
    {
        $mobile = $request->post('mobile/s','','trim');
        $orgId  = Session::get('org.id');

        if ( empty($mobile) ) return [422,'手机号必须'];
        if ( !preg_match('/^1[34578]{1}\d{9}$/',$mobile) ) return [422,'手机号格式不正确'];

        $ret = Db::name('code')->where('mobile',$mobile)->where('status',0)->field('username,password',true)->find();

        if ( !is_null($ret) ) return [400,'该手机号尚有未使用的优惠码,不能重复发送'];
        
        // 发送优惠码
        $code = date('YmdHis') . rand(100000,999999);
        $code = md5($code);
        $code = strtoupper($code);

        $data['code']        = $code;
        $data['org_id']      = $orgId;
        $data['mobile']      = $mobile;
        $data['project_id']  = 0;
        $data['status']      = 0;
        $data['create_time'] = time();
        $data['update_time'] = 0;
        $num = Db::name('code')->insert($data);
        
        if ($num > 0) {
            $bool = Sms::send('SMS_COUPON',$mobile,$code);
            return $bool ? [ 201,[] ] : 500;
        } else {
            return 500;
        }
    }
}